﻿using Framework.Common.ExceptionOperation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PaPaPa.Web.Common.IO
{
    public class FileOperation
    {
        private static Random _random = new Random(DateTime.Now.Millisecond);

        public static string SaveImage(byte[] file, string originalFileName, string saveDir)
        {
            string[] arrPicExt = new string[] { ".jpg", ".jpeg", ".gif", ".png" };
            string extension = string.Empty;

            // 取上载文件后缀名
            if (!string.IsNullOrWhiteSpace(originalFileName))
                extension = (Path.GetExtension(originalFileName) ?? "").ToLower();

            if (!arrPicExt.Contains(extension))
            {
                throw new GException("上传文件扩展名必需为：" + string.Join("/", arrPicExt));
            }
            else
            {
                string attachSubDir = DateTime.Now.ToString("yyyyMMdd");
                saveDir = Path.Combine(saveDir, attachSubDir);

                // 生成随机文件名
                string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + _random.Next(10000) + extension;

                if (!System.IO.Directory.Exists(saveDir))
                    System.IO.Directory.CreateDirectory(saveDir);

                System.IO.FileStream fs = new System.IO.FileStream(Path.Combine(saveDir, fileName), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                fs.Write(file, 0, file.Length);
                fs.Flush();
                fs.Close();

                return Path.Combine(attachSubDir, fileName);
            }
        }
    }
}
